/*******************************************************************************
 * Copyright (c) 2010, 2015 git@git.oschina.net:kaiwill/springstage.git
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.qinyeit.serviceapp.repository.system;

import com.qinyeit.serviceapp.entity.system.ManagementPermission;
import com.qinyetech.springstage.core.entity.Status;
import com.qinyetech.springstage.core.repository.BaseRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

/** 
 * ClassName: ManagementPermissionRepository <br/>
 * Function: 系统权限 <br/> 
 * date: 2015年10月6日 上午11:50:41 <br/> 
 * 
 * @author wuqing 
 * @version  
 * @since JDK 1.7 
 */
public interface ManagementPermissionRepository extends BaseRepository<ManagementPermission, Long> {
	@Query("select sp from ManagementPermission sp order by display_order asc")
	public List<ManagementPermission> findByParentIsNull();


	@Query("select p from ManagementAccount sa join sa.roles r join r.permissions p where sa.id=?1")
	public Set<ManagementPermission> findPermission(Long id);

    @Query("select p.code from ManagementAccount sa join sa.roles r join r.permissions p where sa.account=?1 and p.code is not null")
	public Set<String> findPermission(String account);

	/**
	 * 查询所有权限字符串，初始化使用
	 * @return
	 */
	@Query("select p.code from ManagementPermission p")
    public Set<String> findAllPermissions();

	/**
	 * 统计使用次数
	 * @param id
	 * @return
	 */
	@Query(value="select count(management_permission_id) as total from management_role_permissions where management_permission_id=?1",nativeQuery = true)
	public Long usedCount(Long id);

	@Modifying
	@Query("update ManagementPermission mp set mp.status=?1 where mp.id=?2")
	public void statusSwitch(Status status, Long id);


	/**
	 *  某个角色拥有的所有权限和不拥有的权限，为角色授权的时候使用
	 * @param roleId
	 * @return
	 */
	@Query(value="SELECT p.id id,p.parent_id pid,p.name,r.management_role_id,p.type FROM management_permissions  p LEFT JOIN \n" +
			"(SELECT * FROM `management_role_permissions` rp WHERE rp.management_role_id=?1) r\n" +
			"ON p.id=r.management_permission_id where p.is_deleted=0 order by display_order asc",nativeQuery = true)
	public List<Object[]> findAllPermissionsByRoleId(Long roleId);


	@Transactional
	@Modifying
	@Query(value = "DELETE FROM management_role_permissions WHERE management_role_id=?1",nativeQuery = true)
	void deletedRolePermissions(Long roleId);

	@Transactional
	@Modifying
	@Query(value = "DELETE FROM merchant_role_permissions WHERE role_id=?1",nativeQuery = true)
	void deletedRolebranchPermissions(Long roleId);

}
